package com.boronstream.istar;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.R.bool;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.boronstream.istar.S.IItemTabToday;
import com.boronstream.istar.http.PlayNetworkCenter;
import com.boronstream.istar.http.PlayRequestListener;
import com.boronstream.istar.http.PlayResponse;
import com.boronstream.istar.http.request.HoroscopeRequest;
import com.boronstream.istar.http.response.HoroscopeResponse;
import com.boronstream.istar.model.Horoscope;
import com.boronstream.istar.utils.CommonDefine.IntentAction;
import com.boronstream.istar.utils.CommonDefine.IntentField;
import com.boronstream.istar.utils.CommonDefine.TimeExtra;
import com.boronstream.istar.utils.HelperUtils;
import com.boronstream.istar.utils.Logger;

public interface FragmentToday {

	public static class TodayFragment extends Fragment implements
			PlayRequestListener {
		private static final String TAG = TodayFragment.class.getSimpleName();

		private IItemTabToday self;

		private String starName;

		private Horoscope horoscope;

		private IntentFilter filter = new IntentFilter(
				IntentAction.ACTION_STAR_FILTER_CHANGE);
		private MyReceiver receiver = new MyReceiver();

		public TodayFragment() {
			Logger.d(TAG, "new Instance.");
		}

		public static TodayFragment newInstance() {
			TodayFragment fragment = new TodayFragment();
			// Supply num input as an argument.
			Bundle args = new Bundle();
			args.putInt("num", 0);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			Logger.i(TAG, "onActivityCreated");
		}

		@Override
		public void onAttach(Activity activity) {
			Logger.i(TAG, "onAttach");
			super.onAttach(activity);
			try {
				getActivity().registerReceiver(receiver, filter);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onDetach() {
			Logger.i(TAG, "onDetach");
			super.onDetach();
			try {
				getActivity().unregisterReceiver(receiver);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onResume() {
			super.onResume();
			Logger.i(TAG, "onResume");
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			Logger.i(TAG, "onCreate");
		}

		private void gotoSymbol(String starName){
			try {
				Intent intent = new Intent(getActivity(),StarSymbolActivity.class);
				intent.putExtra(IntentField.STAR_NAME, starName);
				getActivity().startActivity(intent);
			} catch (Exception e) {
			}
		}
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View conView = inflater.inflate(
					com.boronstream.istar.R.layout.i_item_tab_today, container,
					false);
			self = new IItemTabToday(conView);
			horoscope = HelperUtils.getInstance().getHoroscope(getActivity(),
					"h_today");
			this.startGetTodayFortune();
			Logger.w(TAG, "onCreateView:" + self + "," + conView);
			return conView;
		}

		private synchronized void startGetTodayFortune() {
			try {
				SharedPreferences sp = getActivity().getSharedPreferences(
						getString(R.string.app_name), Context.MODE_PRIVATE);
				starName = sp.getString("default_star",
						getString(R.string.default_star));
				Logger.e(TAG, starName + ",horoscope:" + horoscope);
				if (horoscope != null && starName != null
						&& starName.equals(horoscope.getStar_name())) {
					try {
						SimpleDateFormat format = new SimpleDateFormat(
								"yyyy年MM月dd日");
						String dateString = format.format(new Date());
						Logger.d(TAG, "dateString:" + dateString
								+ " updateTime:" + horoscope.getUpdate_time());
						if (dateString.equals(horoscope.getUpdate_time())) {
							this.refreshView(horoscope);
							return;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				HoroscopeRequest request = new HoroscopeRequest();
				request.setStarName(starName);
				request.getRequestParams().put("type", "today");
				PlayNetworkCenter.getInstance().startRequest(request, this);
				self.mProgressBar.setVisibility(View.VISIBLE);
				self.mContentLayout.setVisibility(View.INVISIBLE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void setStarName(String starName) {
			this.starName = starName;
		}

		@Override
		public void onRequestFinished(ResultType resultType,
				PlayResponse response) {
			Logger.i(TAG, "resultType:" + resultType.nativeString);
			self.mProgressBar.setVisibility(View.GONE);

			if (response != null && response instanceof HoroscopeResponse) {
				HoroscopeResponse hrscp = (HoroscopeResponse) response;
				horoscope = hrscp.getHoroscope();
				HelperUtils.getInstance().saveHoroscope(getActivity(),
						horoscope, "h_today");
				Logger.i(TAG, horoscope != null ? horoscope.toString() : "");
			}
			this.refreshView(horoscope);
		}

		public void setHoroscope(Horoscope horoscope) {
			this.horoscope = horoscope;
		}

		private void refreshView(final Horoscope horoscope) {
			if (horoscope != null) {
				try {
					self.mContentLayout.setVisibility(View.VISIBLE);
					self.mProgressBar.setVisibility(View.GONE);
					self.mTitle.setText(horoscope.getStar_name() + ""
							+ horoscope.getUpdate_time() + "运势");
					self.mTvLuckyColor.setText(horoscope.getLucky_color());
					self.mTvLuckyNumber.setText(horoscope.getLucky_number());
					self.mTvFastMatch.setText(horoscope.getFast_match());
					self.mTvFastMatch.setOnClickListener(new View.OnClickListener() {

						
						@Override
						public void onClick(View v) {
							String starName = horoscope.getFast_match();
							String[] names = getActivity().getResources().getStringArray(R.array.star_list);
							boolean ok=false;
							for (String string : names) {
								if (string.equals(starName)) {
									ok=true;
								}
							}
							if (ok) {
								Intent intent = new Intent(getActivity(),StarSymbolActivity.class
										);
								intent.putExtra(IntentField.STAR_NAME, horoscope.getFast_match());
								getActivity().startActivity(intent);
							}
							
						}
					});
					self.mTvLabelDescription.setText("今日概况："
							+ horoscope.getDescription());
					this.refreshAstroImage(horoscope.getStar_name());
					self.mRbOverviewIndex
							.setImageResource(getIndexImg(horoscope
									.getOverview_index()));
					self.mTvOverviewIndex
							.setText(getIndexValue(horoscope.getOverview_index())+"");
					self.mRbHealthIndex.setImageResource(getIndexImg(horoscope
							.getHealth_index()));
					self.mTvHealthIndex.setText(getIndexValue(horoscope.getHealth_index())+"");
					self.mRbLoveIndex.setImageResource(getIndexImg(horoscope
							.getLove_index()));
					self.mTvLoveIndex.setText(getIndexValue(horoscope.getLove_index())+"");
					self.mRbWorkIndex.setImageResource(getIndexImg(horoscope
							.getWork_index()));
					self.mTvWorkIndex.setText(getIndexValue(horoscope.getWork_index())+"");
					self.mRbWealthIndex.setImageResource(getIndexImg(horoscope
							.getWealth_index()));
					self.mTvWealthIndex.setText(getIndexValue(horoscope.getWealth_index())+"");
					self.mTvNoData.setVisibility(View.GONE);
					/**
					 * show Animation
					 */
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							showAnaimation(self.mRbOverviewIndex);
							showAnaimation(self.mRbHealthIndex);
							showAnaimation(self.mRbLoveIndex);
							showAnaimation(self.mRbWealthIndex);
							showAnaimation(self.mRbWorkIndex);
						}
					}, TimeExtra.ONE_SECOND * 2);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			else {
				self.mTvNoData.setVisibility(View.VISIBLE);
				self.mContentLayout.setVisibility(View.GONE);
				self.mProgressBar.setVisibility(View.GONE);
				self.mTvNoData.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						self.mTvNoData.setVisibility(View.GONE);
						startGetTodayFortune();
					}
				});
			}
		}

		private void showAnaimation(ImageView imageView) {
			try {
				Object object = imageView.getDrawable();
				AnimationDrawable animation = (AnimationDrawable) object;
				animation.stop();
				animation.start();
			} catch (Exception e) {
			}
		}

		private String getIndexValue(String string) {
			try {
//				int score = Integer.valueOf(string.replace("%", ""));
//				float _id = ((score + 0.00f)* 5.00f/ 100.00f) ;
//				String value = _id+"";
//				if (value.length()<4) {
//					value=value+"0";
//				}
//				return value;
//				return score+"";
				return string;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "";
		}

		private int getIndexImg(String string) {
			try {
				int score = Integer.valueOf(string.replace("%", ""));
				int _id = 1;
				if (score <= 20) {
					_id = 1;
				} else if (score <= 40) {
					_id = 2;
				} else if (score <= 60) {
					_id = 3;
				} else if (score <= 80) {
					_id = 4;
				} else if (score <= 100) {
					_id = 5;
				}
				return HelperUtils.getInstance().getAnimdByName(getActivity(),
						"rb_" + _id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return 0;
		}

		private void refreshAstroImage(final String starName) {
			if (starName != null) {
				String[] astros = getResources().getStringArray(
						R.array.star_list);
				for (int i = 0; i < astros.length; i++) {
					if (starName.equals(astros[i])) {
						String name = "star_" + i;
						self.mIcon.setImageResource(HelperUtils.getInstance()
								.getDrawableIdByName(getActivity(), name));
						break;
					}
				}
				self.mIcon.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						gotoSymbol(starName);
					}
				});
			}
		}

		private class MyReceiver extends BroadcastReceiver {

			@Override
			public void onReceive(Context context, Intent intent) {
				if (intent != null
						&& IntentAction.ACTION_STAR_FILTER_CHANGE.equals(intent
								.getAction())) {
					startGetTodayFortune();
				}
			}
		}
	}
}